package com.rykj.qxj.server.common.utils.generator;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Type;

import com.rykj.qxj.server.util.object.StringUtils;

/**
 * 生成建表语句
 * 1. 注释可识别 /**..及//
 * 2. 注解目前只识别长度及是否非空
 */
public class SqlUtils {
	public static String generateDdl(Class clazz) {
		StringBuilder sb = new StringBuilder("CREATE TABLE `").append(BaseGeneratorUtils.camel2Underline(clazz.getSimpleName()))
				.append("` (").append("\n");
		String javaTxt = BaseGeneratorUtils.readJavaFile(clazz);
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			String fieldName = BaseGeneratorUtils.camel2Underline(field.getName());
			if(field.getGenericType().getTypeName().indexOf(".model.") != -1){
				fieldName += "_id";
			}
			sb.append("  `").append(fieldName).append("` ");
			/** 判断类型信息 */
			Type type = field.getType();
			switch (type.getTypeName()) {
			case "java.lang.String":
				sb.append("varchar(");
				// 对于字符串考虑注解
				int max = 255;
				Annotation[] annotations = field.getAnnotations();
				/*for(Annotation annotation : annotations){
					if(annotation.annotationType().getName() == "org.hibernate.validator.constraints.Length"){
						Length length = (Length) annotation;
						max = length.max()>0?length.max():max;
					}
				}*/
				sb.append(max).append(") ");
				break;
			case "java.util.Date":
				sb.append("datetime ");
				break;
			case "int":
			case "java.lang.Integer":
			case "long":
			case "java.lang.Long":
				sb.append("int(11) ");
				break;
			case "double":
			case "java.lang.Double":
				sb.append("double ");
				break;
			default: // 关联对象、玫举
				sb.append("varchar(32) ");
			}
			//注解
			Annotation[] annotations = field.getAnnotations();
			for(Annotation annotation : annotations){
				switch(annotation.annotationType().getName()){
				case "org.hibernate.validator.constraints.NotEmpty":
				case "org.hibernate.validator.constraints.NotBlank":
				case "javax.validation.constraints.NotNull":
					sb.append("NOT NULL ");
				}
			}
			
			// 注释
			String note = BaseGeneratorUtils.getJavaAnnotation(javaTxt, field.getName());
			if(StringUtils.isNotEmpty(note)){
				sb.append("COMMENT '").append(note).append("'");
			}
			
			sb.append(",\n");
		}
		sb.append("  PRIMARY KEY (`id`)").append("\n").append(") ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
		// 表注释
		String clazzNote = BaseGeneratorUtils.getJavaAnnotation(javaTxt, clazz.getSimpleName());
		if(StringUtils.isNotEmpty(clazzNote)){
			sb.append("COMMENT='").append(clazzNote).append("';");
		}else{
			sb.append(";");
		}
		return sb.toString();
	}
}
